import React from 'react'
import { Link, Redirect } from 'react-router-dom'
import PropTypes from 'prop-types'
export default class User extends React.Component {
    static propTypes = {
        isLogin: PropTypes.bool,
        error: PropTypes.string,
        makeLogin: PropTypes.func.isRequired,
    }    
    constructor(props){
        super(props);
        this.state = {
            username: '',
            password: ''
        }
        this.handleChange = this.handleChange.bind(this)
        this.handleSubmit = this.handleSubmit.bind(this)
    }
    handleChange(event) {
        this.setState({[event.target.name]: event.target.value})
    }
    handleSubmit(event) {
        this.props.makeLogin(this.state.username, this.state.password)
        event.preventDefault()
    }
    render(){
        let error = null;
        if(this.props.isLogin)
            return <Redirect to='/user'/>;
		if(this.props.error){
			error = <div> Error: {this.props.error}</div>
        }
        
        return(
            <div>
            <form onSubmit={this.handleSubmit} name="login">
                {error}
                <label >username</label>
                <input type="text" name="username" 
                value={this.state.username}
                onChange={this.handleChange}
                />
                <label> password</label>
                <input type="password" name="password" 
                value={this.state.password}
                onChange={this.handleChange}
                />
                <input type="submit" value="login"></input>
            </form>
            <div>Don't have an account? <Link to="/register">Register</Link></div> 
            </div> 
            ) 
        
    }
}